import Api from '../api';
import Tool from "@/libs/tool";
import Cache from "@/libs/cache";
import Store from "@/libs/store";
let tag = {
    id: 0,
    created_at: 0,
    created_by: 0,
    deleted_at: 0,
    name: "",
    updated_at: 0,
    updated_by: 0,
    _isJoinIn: 0
}
const Tag = {
    getInitData() {
        return tag;
    },
    getCacheById(id) {
        let _this = this;
        let cacheModel =  Cache.get("Tag:" + id);
        // cacheModel = _this.isJoinInCheck(cacheModel);
        return cacheModel;
    },
    deleteCacheById(id) {
        Cache.delete("Tag:" + id);
    },
    resetCacheForId(id, cacheModel) {
        let _this = this;
        _this.deleteCacheById(id);
        Cache.set("Tag:" + id, cacheModel, 86400 * 3);
    },
    async getOrSetCacheById(id, updated_at = 0) {
        let _this = this;
        let cacheModel = _this.getCacheById(id);
        // 是否需要更新
        let bool = !cacheModel || updated_at > cacheModel.updated_at;
        if (bool) {
            let res = await Api.post('/tag/default/get-by-id', {id});
            _this.resetCacheForId(id, res.tag);
            cacheModel = _this.getCacheById(id);
        }
        return cacheModel;
    },
    isJoinInCheck(cacheModel) {
        // 是否是已加入的圈子
        if (cacheModel) {
            cacheModel._isJoinIn = 0;
            if (Store.getters['Auth/getUserInfo']._tagIds.includes(cacheModel.id)) {
                cacheModel._isJoinIn = 1;
            }
        }
        return cacheModel;
    },
    joinIn(item) {
        let _this = this;
        uni.showModal({
            title: '提示',
            content: '确定加入圈子['+item.name+']吗？',
            success: function (res) {
                if (res.confirm) {
                    Api.post('/user/tag/join-in', {
                        tagId: item.id
                    }).then(respData => {
                        item._isJoinIn = 1;
                        _this.deleteCacheById(item.id);
                        uni.$u.toast("加入成功");
                    });
                }
            }
        });
    },
    exit(item) {
        let _this = this;
        uni.showModal({
            title: '提示',
            content: '确定退出圈子['+item.name+']吗？',
            success: function (res) {
                if (res.confirm) {
                    Api.post('/user/tag/exit', {
                        tagId: item.id
                    }).then(respData => {
                        item._isJoinIn = 0;
                        _this.deleteCacheById(item.id);
                        uni.$u.toast("退出成功");
                    });
                }
            }
        });
    }
}
export default Tag
